//
//  CJPictureView.swift
//  SinaWeibo
//
//  Created by 程建 on 16/9/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let cellID = "CJPictureViewID"

class CJPictureView: UICollectionView {

    
    var pictureInfos:[CJStatusPictureInfo]? {
        
        didSet{
            
            
            
            //数据一旦发生变化就要刷新数据
        self.reloadData()
        }
        
    }
    
    
    override func awakeFromNib() {
        
        //显示数据,设置数据源对象
        self.dataSource = self
        
        
       // self.backgroundColor = UIColor.red
        
        
        
        
        //注册cell
        self.register(CJPictureCell.self, forCellWithReuseIdentifier: cellID)
        
    }
    
    

}

extension CJPictureView:UICollectionViewDataSource {
    

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CJPictureCell
        
        cell.pictureInfo = self.pictureInfos![indexPath.item]
        
        cell.backgroundColor = UIColor.orange
        return cell
    }

}


//一个文件中可以写多个类
class CJPictureCell: UICollectionViewCell {
    
    var pictureInfo: CJStatusPictureInfo? {
    
        didSet {
            
            //获取URL
            let url = URL(string: (pictureInfo?.wap_pic ?? ""))
            
            iv.sd_setImage(with: url)
            
            //根据判断是否显示gif图片
            gifiocn.isHidden = !url!.absoluteString.hasSuffix(".gif")
        }
        
    }
    
    
    
    //添加一个iv
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.addSubview(iv)
        
        //设置约束
        iv.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView.snp.edges)
        }
        
        self.contentView.addSubview(gifiocn)
        
        gifiocn.snp.makeConstraints { (make) in
            
            make.bottom.right.equalTo(self.contentView)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加一个imageView
    private lazy var iv: UIImageView = {
        
        let iv = UIImageView()
        
        //设置图片样式
        iv.contentMode = .scaleAspectFill
        //需要手动设置裁剪
        iv.clipsToBounds = true
        
        
        return iv
    
    }()
    
    private lazy var gifiocn: UIImageView = UIImageView(image: #imageLiteral(resourceName: "timeline_image_gif"))
    
}

